'''
filename: sql_db
author: yinwenlu
datetime: 2019/10/10 11:58
software: PyCharm
'''
import traceback

from LoggerWarpper import logger
from Redis.redis import RedisConnect
from db import Session, ShopMeituanInfo, ShopInfo, ShopEleInfo, Admin, SuggestParam, datetime, MTSpider, ELESpider, \
    ShopBiddingTarget, func, YesOrderInfo, ShopBidding, BusinessInfo, OperationDaily, AdminShop
from web.service.api_service.public.MyThread import MyThread
from web.service.public.result import resultJson


def updShopInfoNew(**kwargs):
    try:
        shopId = kwargs.get("shopId")
        shopType = kwargs.get("shopType")
        shipTime = kwargs.get("shipTime")

        shop = None
        account = None
        session = Session()
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()

        if shop:
            account = shop.account
            if shipTime:
                shop.shipTime = shipTime
        session.commit()
        session.close()
        return {"code":True,"account":account}
    except:
        return {"code":False,"account":account}

def setSuggestParam(shopId,shopType):
    '''
    将数据获取并且存进数据库
    :param shopId:
    :param shopType:
    :return:
    '''
    '''
    先查询查找当天的记录是否存在
    如果不存在
    1、抓取七天的竞价数据
    2、获取其过往七天的比例，（存在几天的算几天的曝光价格比例，计算前一天的曝光价格比例，做平均）
        1、存在，计算相应的建议参数，存到数据库
        2、不存在，按照今天已经完成的曝光价格比例计算比例
    如果存在，直接返回数据'''
    today=datetime.datetime.now().date().strftime("%Y-%m-%d")
    yesDay=(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
    session=Session()
    if shopType==1:
        suggestParam=session.query(SuggestParam).filter(SuggestParam.day==today,SuggestParam.shopId==shopId,SuggestParam.shopType==shopType).first()
        if suggestParam:
            session.close()
            return  suggestParam.to_dict()
        else:
            cookies, account = session.query(ShopMeituanInfo.cookies, ShopMeituanInfo.account).filter(ShopMeituanInfo.mtId == shopId).first()
            session.close()
            mt = MTSpider(cookies)
            sevenDayInfo=mt.getAvgSevenShopInfo()
            realIncome=mt.getSettleBillList()
            avgIncome=getAvgIncome(realIncome)
            maxPrice=round(sevenDayInfo.get("avgPrice")*1.2,1)#最高价
            minPrice=0.4#最低价
            budget=int(avgIncome*8/100)#预算
            #计算合适的预算曝光比例
            exposurePercentOfSeven=sevenDayInfo.get("showCount",0)/sevenDayInfo.get("cost",1)
            headInfo = getYesOrderInfo(account, day = yesDay)
            if headInfo:
                headInfo = eval(headInfo)
                try:
                    exposurePercentOfToday = float(headInfo.get('ep', {}).get('o', None)) / float(
                        headInfo.get('cot', {}).get('p', None))
                    percent = (exposurePercentOfSeven + exposurePercentOfToday) / 2
                except:
                    percent = exposurePercentOfSeven
            else:
                percent=exposurePercentOfSeven
            targetExposure=int(percent*budget)#目标曝光量
            resultData=dict(shopId=shopId,shopType=shopType,day=today,sevenAvgPrice=sevenDayInfo.get("avgPrice"),
                                   maxPrice=maxPrice,minPrice=minPrice,budget=budget,sevenAvgIncome=avgIncome,
                                   targetExposure=targetExposure,allExposure=sevenDayInfo.get("showCount",0),
                                   allCost=sevenDayInfo.get("cost",1))
            updSuggestParam(**resultData)
            return resultData
    elif shopType==2:
        '''将数据进行平均处理'''
        suggestParam = session.query(SuggestParam).filter(SuggestParam.day == today, SuggestParam.shopId == shopId,
                                                          SuggestParam.shopType == shopType).first()
        if suggestParam:
            session.close()
            return  suggestParam.to_dict()
        else:
            # suggestParamList= session.query(SuggestParam).filter(SuggestParam.shopId == shopId,SuggestParam.shopType == shopType).all()[-7:]
            cookies, account = session.query(ShopEleInfo.cookies, ShopEleInfo.account).filter(
                ShopEleInfo.eleId == shopId).first()
            session.close()
            todayTime = datetime.datetime.now().date()
            ele = ELESpider(cookies)
            # 最高出价为七天的平均出价*1.2
            sevenDayInfo = ele.get7DaysExposure()
            result = ele.gettodayExposure().get("result", {})
            avgPrice = sevenDayInfo.get("averageCost", 0)
            #最高出价
            maxPrice = round(avgPrice * 1.2, 1)
            minPrice = 0.4
            beginDate = (todayTime + datetime.timedelta(days=-7)).strftime("%Y-%m-%d")
            endDate = (todayTime + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
            avgIncome = ele.getHistoryData(beginDate, endDate)
            avgIncome = avgIncome.get("businessData", {}).get("income", {}).get("itemValue", 0)
            avgIncome = round(avgIncome / 7, 2)
            budget = int(avgIncome * 8 / 100)  # 预算
            allTodayExposure = result.get("totalExposureAmount", 0)
            allTodayCost = result.get("totalCost", 1)
            outExposure=0
            outCost=0
            yesExposure=0
            yesCost=0
            headInfo = getEleYesOrderInfo(account, day=today)
            if headInfo:
                for head_info in headInfo:
                    head_info = head_info[0]
                    head_info = eval(head_info)
                    if head_info:
                        outExposure+=float(head_info.get('ep', {}).get('o', None))
                        outCost+=float(head_info.get('cot', {}).get('p', None))
                # 计算合适的预算曝光比例
                try:
                    exposurePercentOfSeven = outExposure / outCost
                except:
                    exposurePercentOfSeven = 12
                try:
                    headInfo = eval(headInfo[0][0])
                    yesExposure=float(headInfo.get('ep', {}).get('o', None))
                    yesCost=float(headInfo.get('cot', {}).get('p', None))
                    exposurePercentOfToday = yesExposure / yesCost
                    percent = (exposurePercentOfSeven + exposurePercentOfToday) / 2
                except:
                    percent = exposurePercentOfSeven
            else:
                percent = allTodayExposure / allTodayCost
            targetExposure = int(budget * percent)
            '''更新数据到数据库'''
            resultData = dict(shopId=shopId, shopType=shopType, day=today, sevenAvgPrice=avgPrice,
                              maxPrice=maxPrice, minPrice=minPrice, budget=budget, sevenAvgIncome=avgIncome,
                              targetExposure=targetExposure, allExposure=yesExposure if yesExposure else allTodayExposure,
                              allCost=yesCost if yesCost else allTodayCost)
            updSuggestParam(**resultData)
            return resultData

def getEleYesOrderInfo(account,day):
    '''
    获取头部信息信息
    :param account:
    :param day:
    :return:
    '''
    session=Session()
    yesOrderInfo=session.query(YesOrderInfo.headInfo).filter(YesOrderInfo.account==account,YesOrderInfo.day<day,YesOrderInfo.headInfo!=None).order_by(
        YesOrderInfo.id.desc()
    ).all()[0:7]
    session.close()
    if yesOrderInfo:
        return yesOrderInfo
    else:
        return False



def setSuggestParamLoad(shopId,shopType):
    '''
        将数据获取并且存进数据库
        :param shopId:
        :param shopType:
        :return:
        '''
    '''先查询查找的记录是否存在
    如果不存在，进行计算，将结果存进数据库，返回数据
    如果存在，直接转换成字典，返回'''
    today = datetime.datetime.now().date().strftime("%Y-%m-%d")
    session = Session()
    if shopType == 1:
        suggestParam = session.query(SuggestParam).filter(SuggestParam.day == today, SuggestParam.shopId == shopId,
                                                          SuggestParam.shopType == shopType).first()
        if suggestParam:
            session.close()
            return suggestParam.to_dict()
        else:
            cookies = session.query(ShopMeituanInfo.cookies).filter(ShopMeituanInfo.mtId == shopId).scalar()
            session.close()
            mt = MTSpider(cookies)
            sevenDayInfo = mt.getAvgSevenShopInfo()
            realIncome = mt.getSettleBillList()
            avgIncome = getAvgIncome(realIncome)
            maxPrice = round(sevenDayInfo.get("avgPrice") * 1.4, 1)  # 最高价
            minPrice = 0.4  # 最低价
            budget = int(avgIncome * 8 / 100)  # 预算
            targetExposure = int(sevenDayInfo.get("showCount", 0) / sevenDayInfo.get("cost", 1) * budget)  # 目标曝光量
            resultData = dict(shopId=shopId, shopType=shopType, day=today, sevenAvgPrice=sevenDayInfo.get("avgPrice"),
                              maxPrice=maxPrice, minPrice=minPrice, budget=budget, sevenAvgIncome=avgIncome,
                              targetExposure=targetExposure, allExposure=sevenDayInfo.get("showCount", 0),
                              allCost=sevenDayInfo.get("cost", 1))
            updSuggestParam(**resultData)
            return resultData
    elif shopType == 2:
        # suggestParam=session.query(SuggestParam).filter(SuggestParam.shopId == shopId,SuggestParam.shopType == shopType).order_by(SuggestParam.id.desc()).first()
        todayTime = datetime.datetime.now().date()
        '''获取今天新的数据，将数据存到数据库'''
        cookies = session.query(ShopEleInfo.cookies).filter(ShopEleInfo.eleId == shopId).scalar()
        ele = ELESpider(cookies)
        # 最高出价为七天的平均出价*1.4
        sevenDayInfo = ele.get7DaysExposure()
        result = ele.gettodayExposure().get("result", {})
        avgPrice = sevenDayInfo.get("averageCost", 0)
        maxPrice = round(avgPrice * 1.4, 1)
        minPrice = 0.4
        beginDate = (todayTime + datetime.timedelta(days=-7)).strftime("%Y-%m-%d")
        endDate = (todayTime + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
        avgIncome = ele.getHistoryData(beginDate, endDate)
        avgIncome = avgIncome.get("businessData", {}).get("income", {}).get("itemValue", 0)
        avgIncome = round(avgIncome / 7, 2)
        budget = int(avgIncome * 8 / 100)  # 预算
        allExposure = result.get("totalExposureAmount", 0)
        allCost = result.get("totalCost", 1)
        targetExposure = int(budget * allExposure / allCost)
        '''更新数据到数据库'''
        resultData = dict(shopId=shopId, shopType=shopType, day=today, sevenAvgPrice=avgPrice,
                          maxPrice=maxPrice, minPrice=minPrice, budget=budget, sevenAvgIncome=avgIncome,
                          targetExposure=targetExposure, allExposure=allExposure,
                          allCost=allCost)
        updSuggestParam(**resultData)

        '''将数据进行平均处理'''
        suggestParamList = session.query(SuggestParam).filter(SuggestParam.shopId == shopId,
                                                              SuggestParam.shopType == shopType).all()[-7:]
        session.close()
        outExposure = 0
        outCost = 0
        for suggest in suggestParamList:
            outExposure += suggest.allExposure
            outCost += suggest.allCost
        outSuggestParam = suggestParamList[len(suggestParamList) - 1]
        outSuggestParam.targetExposure = round(outExposure / outCost * int(outSuggestParam.budget), 2)
        outSuggestParam.allExposure = outExposure
        outSuggestParam.allCost = outCost
        outSuggestParam = outSuggestParam.to_dict()
        return outSuggestParam


def getAvgIncome(data):
    '''
    获取平均的实际营收数据
    :param data:结算与未结算的数据
    :return:
    '''
    #unSetBillList=data.get('unSetBillList',[]).get('dailyBills')[1:] if len(data.get('unSetBillList',[]))!=0 else []
    allBillList=data.get('unSettleBillList',[])+data.get('settleBillList',[])[0:2]#所有的订单组
    allDetailBill=[]
    for billList in allBillList:
        for bill in billList.get('dailyBills',[]):
            if bill.get('dailyBillDate',{})!=datetime.datetime.now().date().strftime("%Y-%m-%d") and bill.get('dailyBillAmount',0)!="0.00":
                allDetailBill.append(bill)
    allIncome=0
    for detailBill in allDetailBill:
        allIncome+=float(detailBill.get("dailyBillAmount",0))
    avgIncome=round(allIncome/len(allDetailBill),2)
    return avgIncome

def updSuggestParam(**kwargs):
    '''
    向数据库添加记录
    :param kwargs:
    :return:
    '''
    try:
        shopId = kwargs.get("shopId",0)
        shopType = kwargs.get("shopType",0)
        day = kwargs.get("day","")
        sevenAvgPrice = kwargs.get("sevenAvgPrice",0)
        maxPrice = kwargs.get("maxPrice",0)
        minPrice = kwargs.get("minPrice",0)
        budget = kwargs.get("budget",0)
        sevenAvgIncome = kwargs.get("sevenAvgIncome",0)
        targetExposure = kwargs.get("targetExposure",0)
        allExposure = kwargs.get("allExposure",0)
        allCost = kwargs.get("allCost",0)
        session = Session()
        suggestParam=session.query(SuggestParam).filter(SuggestParam.shopId==shopId,SuggestParam.shopType==shopType,
                                                        SuggestParam.day==day).first()
        if not suggestParam:
            session.add(
                SuggestParam(
                    shopId = shopId,
                    shopType = shopType,
                    day=day,
                    maxPrice=maxPrice,
                    sevenAvgPrice=sevenAvgPrice,
                    minPrice=minPrice,
                    budget=budget,
                    sevenAvgIncome=sevenAvgIncome,
                    targetExposure=targetExposure,
                    allExposure=allExposure,
                    allCost=allCost
                )
            )
        else:
            if sevenAvgPrice:
                suggestParam.sevenAvgPrice=sevenAvgPrice
            if maxPrice:
                suggestParam.maxPrice=maxPrice
            if minPrice:
                suggestParam.minPrice=minPrice
            if budget:
                suggestParam.budget = budget
            if sevenAvgIncome:
                suggestParam.sevenAvgIncome = sevenAvgIncome
            if targetExposure:
                suggestParam.targetExposure = targetExposure
            if allExposure:
                suggestParam.allExposure = allExposure
            if allCost:
                suggestParam.allCost=allCost
        result=session.commit()
        session.close()
        if result:
            return False
        else:
            return False
    except:
        return False



def getMyShop(bid,day):
    '''
    获取该账号的所有店铺
    :param bid: 加密的密码
    :return:
    '''
    redis = RedisConnect()
    try:
        result = None
        session = Session()
        userName, adminId = session.query(Admin.userName, Admin.id).filter(Admin.bid == bid).first()
        if not userName:
            session.close()
            result = 1000
        elif userName=="super001" or userName =="super01":
            eleShopList = session.query(ShopEleInfo.eleName, ShopEleInfo.shopType, ShopEleInfo.shopId,ShopEleInfo.account, ShopEleInfo.eleId).filter(ShopEleInfo.deleted==0).all()
            mtShopList = session.query(ShopMeituanInfo.mtName, ShopMeituanInfo.shopType, ShopMeituanInfo.shopId,ShopMeituanInfo.account, ShopMeituanInfo.mtId).filter(ShopMeituanInfo.deleted==0).all()
            session.close()
            eleShop = []
            mtShop = []
            mt_keys = []
            ele_keys = []
            for shop in eleShopList:
                ele_keys.append(str(shop[4]) + str(shop[1]) + "setNote")
                eleShop.append({"name": shop[0], "shopType": shop[1], "shopId": shop[2] , "note":None, "account":shop[3]})
            ele_notes = redis.rc.mget(ele_keys)
            i = 0
            for note in ele_notes:
                ele_note = str(note, encoding='utf-8') if note else ""
                eleShop[i]['note'] = ele_note
                i = i + 1
            for shop in mtShopList:
                mt_keys.append(str(shop[4]) + str(shop[1]) + "setNote")
                mtShop.append({"name": shop[0], "shopType": shop[1], "shopId": shop[2],  "note": None, "account":shop[3]})
            mt_notes = redis.rc.mget(mt_keys)
            i = 0
            for note in mt_notes:
                mt_note = str(note, encoding='utf-8') if note else ""
                mtShop[i]['note'] = mt_note
                i = i + 1
            result = {"eleShop": eleShop, "mtShop": mtShop}
        else:
            mtShopList = []#美团店铺返回结果集
            eleShopList = []#饿了么店铺返回结果集
            #先查询admin_shop表，获取当前账户下的所有店铺shopid,店铺种类shoptype，是否删除isdelete
            shopIds = []
            shopIds = session.query(AdminShop.shop_id, AdminShop.shop_type, AdminShop.is_delete)\
                .filter(AdminShop.admin_id == adminId)\
                .all()
            for shop in shopIds:
                if shop.shop_type == 1:
                    mtshop = session.query(ShopMeituanInfo.mtName, ShopMeituanInfo.shopType, ShopMeituanInfo.shopId,
                                 ShopMeituanInfo.account, ShopMeituanInfo.mtId).filter(
                        ShopMeituanInfo.id == shop.shop_id, ShopMeituanInfo.deleted == 0).first()
                    if mtshop:
                        mtShopList.append(mtshop)
                if shop.shop_type == 2:
                    eleshop = session.query(ShopEleInfo.eleName, ShopEleInfo.shopType, ShopEleInfo.shopId,ShopEleInfo.account, ShopEleInfo.eleId).filter(
                ShopEleInfo.id == shop.shop_id, ShopEleInfo.deleted==0).first()
                    if eleshop:
                        eleShopList.append(eleshop)
            session.close()
            eleShop = []
            mtShop = []
            mt_keys = []
            ele_keys = []
            for shop in eleShopList:
                ele_keys.append(str(shop[4]) + str(shop[1]) + "setNote")
                eleShop.append({"name": shop[0], "shopType": shop[1], "shopId": shop[2], "note": None, "account": shop[3]})
            ele_notes = redis.rc.mget(ele_keys)
            i = 0
            for note in ele_notes:
                ele_note = str(note, encoding='utf-8') if note else ""
                eleShop[i]['note'] = ele_note
                i = i + 1
            for shop in mtShopList:
                mt_keys.append(str(shop[4]) + str(shop[1]) + "setNote")
                mtShop.append({"name": shop[0], "shopType": shop[1], "shopId": shop[2], "note": None, "account": shop[3]})
            mt_notes = redis.rc.mget(mt_keys)
            i = 0
            for note in mt_notes:
                mt_note = str(note, encoding='utf-8') if note else ""
                mtShop[i]['note'] = mt_note
                i = i + 1
            result = {"eleShop": eleShop, "mtShop": mtShop}
        return result
    except:
        return False


def addPlansOfShops(shops):
    '''
    将计划的生成情况添加到数组中
    :param shops: 所有的店铺情况
    :return:
    '''
    ct= datetime.datetime.now().date().strftime("%Y-%m-%d %H:%M:%S")
    ele_shops=shops.get('ele',{})
    mt_shops=shops.get('mt',{})
    session=Session()
    for i in range(len(ele_shops)):
        result=session.query(func.count(ShopBiddingTarget.id)).filter(ShopBiddingTarget.shopid==ele_shops[i]['shopId'],
                                                                      ShopBiddingTarget.type==ele_shops[i]['shoptype'],
                                                                      ShopBiddingTarget.exposureTime>ct).scalar()
        if result>0:
            ele_shops[i]['plans']=1
    for i in range(len(mt_shops)):
        result = session.query(func.count(ShopBiddingTarget.id)).filter(ShopBiddingTarget.shopid == mt_shops[i]['shopId'],
                                                                        ShopBiddingTarget.type == mt_shops[i]['shoptype'],
                                                                        ShopBiddingTarget.exposureTime > ct).scalar()
        if result > 0:
            mt_shops[i]['plans'] = 1

    return {"eleShops":ele_shops,"mtShops":mt_shops}

def getMOrEBsaeInfo(shopType,cookies):
    '''
    获取美团或者饿了么的推广状态和营业时间
    :param shopType:
    :param cookies:
    :return:
    '''
    '''获取时间时会产生的问题
    1、判断接口返回的数据是否正确，即进行cookie是否失效以及接口是否发生改变
    2、ele如果返回的数据为空，表明返回的数据是00:00-23:59'''
    resultDict={}
    exLog=''
    date=None
    error=''
    try:
        if shopType==1:
            mt=MTSpider(cookies)
            details=mt.getDetail(None)
            if not details:
                exLog+="店铺断开绑定"
                error=1
            else:
                shopStatus=details.get("status")
                shipTime=mt.getShopStatus(None).get("shippingTimeDesc","")
                date = {"shipTime": shipTime, "shopStatus": shopStatus}
        if shopType==2:
            ele=ELESpider(cookies)
            shopstatus = ele.getShopStatus()
            result = shopstatus.get("result", [])
            if not result:
                exLog += "店铺断开绑定"
                error = 1
            else:
                result = result[0]
                detail = result.get("detail", {})
                shiptimeDesc = ''
                for shiptime in detail.get("businessHours", []):
                    stime = (shiptime.get("startTime", '') + '-' + shiptime.get("endTime", ''))
                    shiptimeDesc += (stime + ',')
                shipTime = shiptimeDesc[:-1]
                if not shipTime:
                    shipTime = "00:00-23:59"
                shopStatus = ele.getAdPrice().get("status")
                shopStatus = 0 if shopStatus == "OPEN" else 1
                date = {"shipTime": shipTime, "shopStatus": shopStatus}
        resultDict=resultJson(date,6000,exLog,error)
    except:
        resultDict=resultJson("",2000,"未知错误",1)

    return resultDict


def getMOrEBsaeInfo(shopType,cookies,ip=None):
    '''
    获取美团或者饿了么的推广状态和营业时间
    :param shopType:
    :param cookies:
    :param ip:
    :return:
    '''
    '''获取时间时会产生的问题
    1、判断接口返回的数据是否正确，即进行cookie是否失效以及接口是否发生改变
    2、ele如果返回的数据为空，表明返回的数据是00:00-23:59'''
    resultDict={}
    exLog=''
    date=None
    error=''
    try:
        if shopType==1:
            mt=MTSpider(cookies)
            details=mt.getDetail(None)
            if not details:
                exLog+="店铺断开绑定"
                error=1
            else:
                shopStatus=details.get("status")
                shipTime=mt.getShopStatus(None).get("shippingTimeDesc","")
                date = {"shipTime": shipTime, "shopStatus": shopStatus}
        if shopType==2:
            ele=ELESpider(cookies)
            shopstatus = ele.getShopStatus()
            result = shopstatus.get("result", [])
            if not result:
                exLog += "店铺断开绑定"
                error = 1
            else:
                result = result[0]
                detail = result.get("detail", {})
                shiptimeDesc = ''
                for shiptime in detail.get("businessHours", []):
                    stime = (shiptime.get("startTime", '') + '-' + shiptime.get("endTime", ''))
                    shiptimeDesc += (stime + ',')
                shipTime = shiptimeDesc[:-1]
                if not shipTime:
                    shipTime = "00:00-23:59"
                shopStatus = ele.getAdPrice().get("status")
                shopStatus = 0 if shopStatus == "OPEN" else 1
                date = {"shipTime": shipTime, "shopStatus": shopStatus}
        resultDict=resultJson(date,6000,exLog,error)
    except:
        resultDict=resultJson("",2000,"未知错误",1)
    return resultDict

def getMOrEBsaeInfoCheck(shopType,cookies,ip=None):
    '''
    获取美团或者饿了么的推广状态和营业时间
    :param shopType:
    :param cookies:
    :param ip:
    :return:
    '''
    '''获取时间时会产生的问题
    1、判断接口返回的数据是否正确，即进行cookie是否失效以及接口是否发生改变
    2、ele如果返回的数据为空，表明返回的数据是00:00-23:59'''
    resultDict={}
    exLog=''
    date=None
    error=''
    spider = None
    try:
        if shopType==1:
            mt=MTSpider(cookies, ip=ip)
            spider = mt
            details=mt.getDetail()
            if not details:
                exLog+="店铺断开绑定"
                error=1
            else:
                shopStatus=details.get("status")
                shipTime=mt.getShopStatus(None).get("shippingTimeDesc","")
                date = {"shipTime": shipTime, "shopStatus": shopStatus}
        if shopType==2:
            ele=ELESpider(cookies)
            spider = ele
            shopstatus = ele.getShopStatus()
            result = shopstatus.get("result", [])
            if not result:
                exLog += "店铺断开绑定"
                error = 1
            else:
                result = result[0]
                detail = result.get("detail", {})
                shiptimeDesc = ''
                for shiptime in detail.get("businessHours", []):
                    stime = (shiptime.get("startTime", '') + '-' + shiptime.get("endTime", ''))
                    shiptimeDesc += (stime + ',')
                shipTime = shiptimeDesc[:-1]
                if not shipTime:
                    shipTime = "00:00-23:59"
                shopStatus = ele.getAdPrice().get("status")
                shopStatus = 0 if shopStatus == "OPEN" else 1
                date = {"shipTime": shipTime, "shopStatus": shopStatus}
        resultDict=resultJson(date,6000,exLog,error)
    except:
        resultDict=resultJson("",2000,"未知错误",1)
    return resultDict, spider
def closeOrOpenShopBidding(shopId,shopType,status=0):
    '''
    关闭打开竞价系统或者推广
    :param shopId:
    :param shopType:
    :param status: 0关闭竞价系统和推广，1打开竞价系统和推广
    :return:
    '''
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
    session.close()
    try:
        if ele:
            cookies = ele.cookies
            eleSpider = ELESpider(cookies)
            eleSpider.changeAdstatus(abs(status-1))#1关闭推广，0打开推广
        elif mt:
            cookies = mt.cookies
            mtSpider = MTSpider(cookies)
            mtSpider.changeAdstatus(abs(status-1))#1关闭推广，0打开推广
        return True
    except:
        return False

def changeShopGuard(shopId,shopType,status):
    '''
    开启关闭监测系统
    :param shopId:
    :param shopType:
    :param status: 0、关闭监测系统，1、打开监测系统
    :return:
    '''
    try:
        result=None
        session=Session()
        if shopType==1:
            result=session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId==shopId).update({ShopMeituanInfo.guard:int(status)})
        elif shopType==2:
            result = session.query(ShopEleInfo).filter(ShopEleInfo.eleId==shopId).update({ShopEleInfo.guard: int(status)})
        session.commit()
        session.close()
        if result:
            return True
        else:
            return  False
    except:
        return False


def updShopNote(shopId,shopType,note):
    '''
    更新店铺的日志
    :param shopId:
    :param shopType:
    :param note: 备注信息
    :return:
    '''
    day=datetime.datetime.now().date().strftime("%Y-%m-%d")
    try:
        session=Session()
        account=None
        if shopType==1:
            account=session.query(ShopMeituanInfo.account).filter(ShopMeituanInfo.mtId==shopId,ShopMeituanInfo.shopType==shopType).scalar()
        if shopType==2:
            account=session.query(ShopEleInfo.account).filter(ShopEleInfo.eleId==shopId,ShopEleInfo.shopType==shopType).scalar()
        yes_order_info = session.query(YesOrderInfo).filter(YesOrderInfo.account==account,YesOrderInfo.day==day).first()
        if yes_order_info:
            yes_order_info.note=note
        else:
            session.add(YesOrderInfo(
                account=account,
                day=day,
                note=note
            ))
        session.commit()
        session.close()
        return True
    except:
        return False
def updShopNoteRedis(shopId, shopType, note):
    """
    更新日志到redistribution缓存中
    :param shopId:
    :param shopType:
    :param note:
    :return:
    """
    redis = RedisConnect()
    res = redis.set(str(shopId) + str(shopType) + "setNote", note)
    return True if res else False

def loadShopNote(shopId,shopType,day):
    '''
    获取该店铺当当前的日志
    :param shopId:
    :param shopType:
    :param day:
    :return:
    '''
    try:
        session=Session()
        account = None
        if shopType == 1:
            account = session.query(ShopMeituanInfo.account).filter(ShopMeituanInfo.mtId == shopId,
                                                                    ShopMeituanInfo.shopType == shopType).scalar()
        if shopType == 2:
            account = session.query(ShopEleInfo.account).filter(ShopEleInfo.eleId == shopId,
                                                                ShopEleInfo.shopType == shopType).scalar()
        note=session.query(YesOrderInfo.note).filter(YesOrderInfo.account==account,YesOrderInfo.day==day).scalar()
        session.close()
        if note:
            return note
        else:
            return False
    except:
        return False



def getShopBiddingYester(shopid, today, type):
    '''

    :param shopid:
    :param today: 获取昨天最后一条的竞价记录，时间为今日零点
    :param type:
    :return:
    '''
    try:
        yes=(datetime.datetime.strptime(today,"%Y-%m-%d %H:%M:%S")+datetime.timedelta(days=-1)).strftime("%Y-%m-%d %H:%M:%S")
        session = Session()
        shopBidding = session.query(ShopBidding).filter(ShopBidding.shopid == shopid,
                                                        ShopBidding.biddingTime < today,
                                                        ShopBidding.biddingTime>yes,
                                                        ShopBidding.shoptype == type, ).order_by(
            ShopBidding.id.desc()).first()
        session.close()
        return shopBidding
    except:
        logger.warning(traceback.format_exc())

def getShopBiddingYesterwithSession(session,shopid, today, type):
    '''

    :param shopid:
    :param today: 获取昨天最后一条的竞价记录，时间为今日零点
    :param type:
    :return:
    '''
    try:
        yes=(datetime.datetime.strptime(today,"%Y-%m-%d %H:%M:%S")+datetime.timedelta(days=-1)).strftime("%Y-%m-%d %H:%M:%S")
        shopBidding = session.query(ShopBidding).filter(ShopBidding.shopid == shopid,
                                                        ShopBidding.biddingTime < today,
                                                        ShopBidding.biddingTime>yes,
                                                        ShopBidding.shoptype == type, ).order_by(
            ShopBidding.id.desc()).first()
        return shopBidding
    except:
        logger.warning(traceback.format_exc())


def getYesOrderInfo(account,day):
    '''
    获取头部信息信息
    :param account:
    :param day:
    :return:
    '''
    session=Session()
    yesOrderInfo=session.query(YesOrderInfo.headInfo).filter(YesOrderInfo.account==account,YesOrderInfo.day==day).scalar()
    session.close()
    if yesOrderInfo:
        return yesOrderInfo
    else:
        return False

def getYesOrderInfowithSession(session,account,day):
    '''
    获取头部信息信息
    :param account:
    :param day:
    :return:
    '''
    yesOrderInfo=session.query(YesOrderInfo.headInfo).filter(YesOrderInfo.account==account,YesOrderInfo.day==day).scalar()
    if yesOrderInfo:
        return yesOrderInfo
    else:
        return False

def updLastShopBidding(*args,**kwargs):
    '''
    更新竞价日志中的最后一条记录
    :param args: shopId,shopType
    :param kwargs:
    :return:
    '''
    shop_id,shopType=args
    ct=datetime.datetime.now().strftime("%Y-%m-%d")
    dawnTime=ct+" 00:00:00"
    replenishnum=kwargs.get("replenishnum",0)
    session=Session()
    shopBidding=session.query(ShopBidding).filter(ShopBidding.biddingTime>dawnTime,ShopBidding.shopid==shop_id,
                                                  ShopBidding.shoptype==shopType).order_by(ShopBidding.id.desc()).first()
    if shopBidding:
        shopBidding.replenishNum=replenishnum
        session.commit()
        session.close()
        return True
    else:
        session.close()
        return False


def getMtShops(deleted=0):
    '''
    获取所有删除或者未删除的店铺信息
    :param deleted:
    :return:
    '''
    try:
        session=Session()
        mtShops=session.query(ShopMeituanInfo).filter(ShopMeituanInfo.deleted==deleted).all()
        session.close()
        if mtShops:
            return mtShops
        else:
            return 1000
    except:
        bugDetail="未删除" if deleted==0 else "删除"
        logger.info("获取{}店铺失败".format(bugDetail))
        return False

def getEleShops(deleted=0):
    '''
    获取所有删除或者未删除的店铺信息
    :param deleted:
    :return:
    '''
    try:
        session=Session()
        eleShops=session.query(ShopEleInfo).filter(ShopEleInfo.deleted==deleted).all()
        session.close()
        if eleShops:
            return eleShops
        else:
            return 1000
    except:
        bugDetail="未删除" if deleted==0 else "删除"
        logger.info("获取{}店铺失败".format(bugDetail))
        return False

def formatAdtAndSpt(shipTime):
    '''
    获取正确格式的推广时间和营业时间数组
    :param shipTime:
    :return: [],[]
    '''
    try:
        shipTimeResult=[]
        adTimeResult=[]
        shipTimes=shipTime.split(",")
        if shipTimes[-1]=='':
            shipTimes=shipTimes[0:-1]
        '''将后面时间点小于前面时间点的时间段分成两个时间段，
                并且如果前一个时间段的最后时间与后一个时间段的第一个时间相等，进行合并'''
        for everyShipTime in shipTimes:
            shopT,shipT=divideShipTime(everyShipTime)
            adTimeResult+=shopT
            shipTimeResult+=shipT
        if adTimeResult=={} or shipTimeResult==[]:
            return resultJson("", 2000, "格式化时间错误", 1)
        return  resultJson({"adTimeResult":adTimeResult,"shipTimeResult":shipTimeResult}, 6000, "格式化时间正确",0)
    except:
        return resultJson("", 2000, "格式化时间错误",1)





def divideShipTime(everyShipTime):
    '''
    跨越24：00的时间段分成两个时间段
    :param everyShipTime:
    :return:[]
    '''
    shipTimeList=[]
    shopTimeList=[]
    timePoint=everyShipTime.split("-")
    endTimeStr = ''
    if timePoint[1] == '00:00' or timePoint[1] == '24:00':
        endTimeStr = '23:59'
    else:
        endTimeStr = timePoint[1]
    baseTime=datetime.datetime.now().strftime("%Y-%m-%d")
    if timePoint[0]>endTimeStr:
        startOne=baseTime+" "+"00:00"+":00"
        startTwo=baseTime+" "+timePoint[0]+":00"
        endOne=baseTime+" "+timePoint[1]+":00"
        #endTwo=baseTime+" "+"23:50"+":00"
        startOne=formateTimeM(startOne,10)
        startTwo=formateTimeM(startTwo,10)
        endOne=formateTimeM(endOne,-10)
        shipTimeList.append(timePoint[0] + '-' + timePoint[1])
        if endOne != "00:00":
            shopTimeList.append({"s": startOne, "e": endOne, "p": '1'})
       # shipTimeList.append(timePoint[0]+"-23:59")
        shopTimeList.append({"s": startTwo, "e": "23:50", "p": '1'})
    else:
        shipTimeList.append(timePoint[0]+"-"+timePoint[1])
        if endTimeStr=="23:59":
            endOne="23:50"
        else:
            endOne = baseTime + " " + timePoint[1] + ":00"
            endOne=formateTimeM(endOne,-10)
        startOne = baseTime+" "+timePoint[0]+":00"
        startOne = formateTimeM(startOne, 10)
        if startOne!="00:00":
            shopTimeList.append({"s": startOne, "e": endOne, "p": '1'})
    return shopTimeList,shipTimeList

def checkAndcorrectTime(shopid,shopType,adTime,shipTime,adTimeList,shipTimeList):
    '''
    对比最新的推广时间和营业时间，并把不正确的时间进行更新
    :param shopid:
    :param shopType:
    :param adTime:
    :param shipTime:
    :param adTimeList:
    :param shipTimeList:
    :return:
    '''
    try:
        resultDict ={}
        shipTimeStr=''
        for i in range(len(shipTimeList)-1):
            shipTimeStr+=(shipTimeList[i]+',')
        shipTimeStr+=shipTimeList[-1]
        if shipTime==shipTimeStr and adTime==adTimeList:
            resultDict= resultJson("",6001,"正确",0)
        else:
            result=updShopTime(shopid,shopType,adTimeList,shipTimeStr)
            if result==1000:
                resultDict= resultJson("",1000,"没有该店铺",1)
            elif not result:
                resultDict = resultJson("", 2000, "未知错误",1)
            else:
                resultDict = resultJson("", 6000, "营业推广时间错误已修正",1)
    except:
        resultDict = resultJson("", 2000, "更新营业时间未知错误",1)
    return resultDict



def updShopTime(shopid,shopType,adTimeList,shipTimeStr):
    '''
    更新营业时间和推广时间段
    :param shopid:
    :param shopType:
    :param adTimeList:
    :param shipTimeStr:
    :return:
    '''
    try:
        session=Session()
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopid,ShopMeituanInfo.shopType == shopType).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopid, ShopEleInfo.shopType == shopType).first()
        if shop and shop.deleted==0:
            if shop.isremake == 0:
                shop.adTime=adTimeList
            shop.shipTime=shipTimeStr
            shop.isenable=1
            session.commit()
            session.close()
            return 6000
        else:
            session.close()
            return 1000
    except:
        logger.info("更新营业推广时间失败")
        return False

def checkAndCorrectBiddingStatus(adTimeList,spider,shopStatus,ct,cDay,shopType):
    '''
    检查并纠正系统的竞价状态，店铺的推广状态
    :param adTimeList:
    :param spider:
    :param shopStatus:
    :return:
    '''
    resultDict = {}
    exLog='平台开关状态正确'
    error=0
    try:
        isInAdTime=IsInAdTime(adTimeList,ct,cDay)
        if isInAdTime:
            if shopStatus!=0:
                error=1
                if shopType==2:
                    blance = spider.getBlance()
                    if blance<=5:
                        exLog += "饿了么店铺余额过低无法打开推广"
                else:
                    exLog+="推广时间段未打开推广已修正"
                spider.changeAdstatus(0)
        else:
            if shopStatus==0:
                error=1
                exLog += "非推广时间段打开推广已修正"
                spider.changeAdstatus(1)
        resultDict=resultJson("", 6000, exLog,error)
    except:
        resultDict=resultJson("", 2000, "未知错误",1)
    return resultDict


def IsInAdTime(shiptime,ct,cDay):
    '''
    判断是否在营业时间
    :param shiptime:
    :return:
    '''

    try:
        shipTimes = eval(shiptime)
    except:
        shipTimes =shiptime
    # if not shiptime and not ad:return True
    # if not shiptime and ad:return False

    for shiptime in shipTimes:
        starttime=shiptime.get("s")
        endtime =shiptime.get("e")
        if starttime and endtime:
            st = cDay + ' ' + starttime + ':00'
            et = cDay + ' ' + endtime + ':00'
            if  ct>= st and  ct<= et:
                return True
    return  False

def checkAndCorrectPlans(shopid,shopType,cDay):
    '''
    获取今日计划的所有记录，进行判断是否发生错误
    :param shopid:
    :param shopType:
    :param cDay:
    :return:
    '''
    resultDict = {}
    exLog='正确'
    error=0
    lenOfPlans = 10#检查的记录条数
    try:
        session=Session()
        plansOfPeriodTarget=session.query(ShopBiddingTarget.exposureNum).filter(
            ShopBiddingTarget.shopid==shopid,ShopBiddingTarget.type==shopType,ShopBiddingTarget.exposureTime>=cDay+" 00:00:00").all()[0:lenOfPlans]
        session.close()
        if len(plansOfPeriodTarget) == 0:
            exLog='当前未生成计划'
            error=1
        else:
            error = 1
            exLog = '该店铺计划数据错误'
            for planOfTarget in plansOfPeriodTarget:
                if int(planOfTarget[0]) > 0:
                    exLog='正确'
                    error = 0
        resultDict = resultJson("", 6000, exLog,error)
    except:
        resultDict = resultJson("", 2000, "检查计划系统错误",1)

    return resultDict

def checkBidding(shopid,shopType,cDay,ct,adTimeList):
    '''
    检查竞价日志
    :param shopid:
    :param shopType:
    :param cDay:
    :param adTimeList:
    :return:
    '''
    resultDict = {}
    try:
        session=Session()
        biddingList=session.query(ShopBidding).filter(ShopBidding.shopid==shopid,ShopBidding.shoptype==shopType,
                                                       ShopBidding.biddingTime>=cDay+" 00:00:00").all()
        session.close()
        if IsInAdTime(adTimeList,ct,cDay):
            if len(biddingList)>=1:
                resultDict=resultJson("","6000","日志初步检查正确",0)
            else:
                resultDict=resultJson("","2002","该店产生日志错误",1)
        else:
            try:
                adTimeList=eval(adTimeList)
            except:
                adTimeList=adTimeList
            if len(adTimeList)==1:
                if len(biddingList)>=1:
                    resultDict=resultJson("","2002","该店产生日志错误",1)
                else:
                    resultDict = resultJson("", "6000", "日志初步检查正确",0)
    except:
        resultDict = resultJson("", "2000", "检查日志系统错误",1)

    return  resultDict


def formateTimeM(timeStr,offset):
    '''

    :param timeStr:
    :param offset:
    :return:
    '''
    timeMid=(datetime.datetime.strptime(timeStr,"%Y-%m-%d %H:%M:%S")+datetime.timedelta(minutes=offset))
    timeM=timeMid.strftime("%M")
    timeH= timeMid.strftime("%H")
    timeMToInt=int(int(timeM) / 10) * 10
    if timeMToInt==0:
        timeMToInt="00"
    endOne=timeH + ":" + str(timeMToInt)
    return endOne


def getMyShopBlance(bid):
    '''
    获取该账号的所有店铺的余额信息
    :param bid: 加密的密码
    :return:
    '''
    try:
        result = None
        session = Session()
        userName, adminId = session.query(Admin.userName, Admin.id).filter(Admin.bid == bid).first()
        if not userName:
            session.close()
            result = 1000
        #522a26aa7080e169cd2eeb8af36a673f
        elif userName=="super001":
            eleShopList = session.query(ShopEleInfo.eleName, ShopEleInfo.shopType, ShopEleInfo.shopId,ShopEleInfo.account, ShopEleInfo.cookies).filter(ShopEleInfo.deleted==0).all()
            mtShopList = session.query(ShopMeituanInfo.mtName, ShopMeituanInfo.shopType, ShopMeituanInfo.shopId,ShopMeituanInfo.account, ShopMeituanInfo.cookies).filter(ShopMeituanInfo.deleted==0).all()
            eleShop = []
            mtShop = []
            threadList = []
            for i in range(0, len(eleShopList)):
                try:
                    t = MyThread(getEleShopBlance, args=(eleShopList[i],))
                    threadList.append(t)
                    t.start()
                except:
                    continue
            for t in threadList:
                t.join()  # 一定要join，不然主线程比子线程跑的快，会拿不到结果
                if t.get_result():
                    eleShop.append(t.get_result())
            threadList = []
            for i in range(0, len(mtShopList)):
                try:
                    t = MyThread(getMtShopBlance, args=(mtShopList[i],))
                    threadList.append(t)
                    t.start()
                except:
                    continue
            for t in threadList:
                t.join()  # 一定要join，不然主线程比子线程跑的快，会拿不到结果
                if t.get_result():
                    mtShop.append(t.get_result())
            result = {"eleShop": eleShop, "mtShop": mtShop}
        else:
            mtShopList = []
            eleShopList = []
            shopIds = []
            shopIds = session.query(AdminShop.shop_id, AdminShop.shop_type, AdminShop.is_delete)\
                .filter(AdminShop.admin_id == adminId)\
                .all()
            for shop in shopIds:
                if shop.shop_type == 1:
                    mtshop = session.query(ShopMeituanInfo.mtName, ShopMeituanInfo.shopType, ShopMeituanInfo.shopId,
                                 ShopMeituanInfo.account, ShopMeituanInfo.cookies).filter(
                        ShopMeituanInfo.id == shop.shop_id, ShopMeituanInfo.deleted == 0).first()
                    if mtshop:
                        mtShopList.append(mtshop)
                if shop.shop_type == 2:
                    eleshop = session.query(ShopEleInfo.eleName, ShopEleInfo.shopType, ShopEleInfo.shopId,ShopEleInfo.account, ShopEleInfo.cookies).filter(
                ShopEleInfo.id == shop.shop_id, ShopEleInfo.deleted==0).first()
                    if eleshop:
                        eleShopList.append(eleshop)
            session.close()
            eleShop = []
            mtShop = []
            threadList = []
            for i in range(0,len(eleShopList)):
                try:
                    t = MyThread(getEleShopBlance, args=(eleShopList[i],))
                    threadList.append(t)
                    t.start()
                except:
                    continue
            for t in threadList:
                t.join()  # 一定要join，不然主线程比子线程跑的快，会拿不到结果
                if t.get_result():
                    eleShop.append(t.get_result())
            threadList = []
            for i in range(0, len(mtShopList)):
                try:
                    t = MyThread(getMtShopBlance, args=(mtShopList[i],))
                    threadList.append(t)
                    t.start()
                except:
                    continue
            for t in threadList:
                t.join()  # 一定要join，不然主线程比子线程跑的快，会拿不到结果
                if t.get_result():
                    mtShop.append(t.get_result())
            result = {"eleShop": eleShop, "mtShop": mtShop}
        session.close()
        return result
    except:
        return False

def getEleShopBlance(shop):
    try:
        ele = ELESpider(shop[4])
        blance = ele.getBlance()
        note = ""
        result = 0
        if blance <= 20:
            note = "当前余额为 {} 元，请及时充值".format(blance)
            result = {"name": shop[0], "shopType": shop[1], "shopId": shop[2], "note": note, "blance": blance}
    except:
        result = {"name": shop[0], "shopType": shop[1], "shopId": shop[2], "note": "店铺断开绑定", "blance": None}
    return result

def getMtShopBlance(shop):
    try:
        mt = MTSpider(shop[4])
        blance = mt.getBlance() / 100
        result = 0
        note = ""
        if blance <= 20:
            note = "当前余额为 {} 元，请及时充值".format(blance)
            result = {"name": shop[0], "shopType": shop[1], "shopId": shop[2], "note": note, "blance": blance}
    except:
        result = {"name": shop[0], "shopType": shop[1], "shopId": shop[2], "note": "店铺断开绑定", "blance": None}
    return result

def updShopInfoOfLock(account, shopType, lock):
    """
    更新是否锁定推广时间
    :param account:
    :param shopType:
    :param lock:
    :return:
    """
    try:
        session = Session()
        if shopType == 1:
            rest = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).update({ShopMeituanInfo.isremake: lock})
        else:
            rest = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).update({ShopEleInfo.isremake: lock})
        session.commit()
        session.close()
        if rest:
            return True
        else:
            return False
    except:
        return True


def getBiddingDateFromOpet(shopid):
    """
    获取shopid店铺的所有接口操作日志
    :param shopid:
    :param status: 智能推广 0：100   定时定价 1：010  手动推广 2：001
    :return:
    """
    session = Session()
    try:
        opet_daily = session.query(OperationDaily).filter(OperationDaily.shopId == shopid, OperationDaily.apiName == '/api/v1/chart/shop/setStatus').all()
        session.close()
        return opet_daily
    except:
        session.rollback()
        session.close()
        return False

def getHeadInfoData(shopid):
    """
    获取当前账号的所有的headInfo
    :param shopid:
    :return:
    """
    session = Session()
    try:
        account = session.query(ShopMeituanInfo.account).filter(ShopMeituanInfo.mtId == shopid).first()[0]
        headInfos = session.query(YesOrderInfo.headInfo, YesOrderInfo.day).filter(YesOrderInfo.account == account).all()
        session.close()
        return headInfos
    except:
        session.rollback()
        session.close()
        return False

def getBusinessInfo(shopid):
    """
    获取该店铺的所有录店之前的运营数据
    :param shopid:
    :return:
    """
    session = Session()
    try:
        business_infos = session.query(BusinessInfo).filter(BusinessInfo.shopId == shopid).all()
        session.close()
        return business_infos
    except:
        session.rollback()
        session.close()
        return False

def saveBiddingDataToBases(shopid, biddingdata):
    """
    将理想的运营效果存到数据库
    :param shopid:
    :param biddingdata:
    :return:
    """
    session = Session()
    try:
        shop_meituan_info = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopid).first()
        shop_meituan_info.result = biddingdata
        session.commit()
        session.close()
        return True
    except:
        session.rollback()
        session.close()
        return False
def getShopInfoByShopId(shopId, shopType):
    '''
    获取美团或者饿了么的店铺信息
    :param shopId: 店铺的id
    :param shopType: 店铺的种类   1是美团，2是饿了么
    :return:
    '''
    shopInfo = {"id": shopId, "cookies": None, "account": None, "ip": None}
    session = Session()
    if shopType == 1:
        shopInfo['cookies'], shopInfo['account'], shopInfo['ip'] = session.query(ShopMeituanInfo.cookies,
                                                                 ShopMeituanInfo.account, ShopMeituanInfo.ip).filter(ShopMeituanInfo.mtId == shopId).first()
    else:
        shopInfo['cookies'], shopInfo['account'] = session.query(ShopEleInfo.cookies, ShopEleInfo.account).filter(
            ShopEleInfo.cookies != '', ShopEleInfo.eleId == shopId).scalar()
    session.close()
    if shopInfo:
        return shopInfo
    else:
        return False

def getAllShopInfoByShopId(shopId, shopType):
    """
    根据shopId和shopType获取该店铺的所有信息
    :param shopId:
    :param shopType:
    :return:
    """
    session = Session()
    try:
        if shopType == 1:
            shopInfo = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shopInfo = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
        session.close()
        return shopInfo
    except:
        session.rollback()
        session.close()
        return None


def getAccountByIdAndShopType(shopId, shopType):
    """

    :param shopId:
    :param shopType:
    :return:
    """
    session = Session()
    if shopType == 1:
        shop = session.query(ShopMeituanInfo.account, ShopMeituanInfo.adTime).filter(ShopMeituanInfo.mtId == shopId).first()
    else:
        shop = session.query(ShopEleInfo.account, ShopEleInfo.adTime).filter(ShopEleInfo.eleId == shopId).first()
    session.close()
    return shop[0], shop[1]